<?php
/**
 * Database class
 * Controls the interactions with the database
 */
namespace PUF;

class Database {
	private $connection = null;
	
	private $host = null;
	
	private $user = null;
	
	private $password = null;
	
	private $database = null;
	
	/**
	 * Database. Contains the only instance
	 */
	private static $instance = null;
	
	/**
	 * Returns the only instance
	 */
	public static function getInstance() {
		if (!self::$instance) {
			self::$instance = new Database();
		}
		
		return self::$instance;
	}
	
	/**
	 * Initializes database connection 
	 */
	private function connect() {
		$this->connection = mysqli_connect(
			$this->host,
			$this->user, 
			$this->password,
			$this->database
		);
		if ($this->connection->connect_errno) {
		    throw new \Exception(
				__METHOD__ . '() => Failed to connect to MySQL: '
				. $this->connection->connect_error
			);
		}
	}
	
	public function addConnection($host, $user, $password, $database) {
		$this->host = $host;
		$this->user = $user;
		$this->password = $password;
		$this->database = $database;
	}
	
	public function query($sql, $model = null) {
		if (!$this->connection) {
			$this->connect();
		}
		
		if (!$result = $this->connection->query($sql)) {
			throw new \Exception(
				__METHOD__ . '() => MySQL Error: '
				. $this->connection->error
				. ' SQL: "' . $sql . '"'
			);
		}
		
		return new DatabaseIterator($result, $model);
	}
}